import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { message } from "antd";
import store from "@/store";

// 约定前后端交互的格式
export interface ResType<T = ResDataType> {
    code: number;
    message?: string;
    data?: T;
}

export type ResDataType = Record<string, any>;

/** 配置axios实例 */
const service: AxiosInstance = axios.create({
    baseURL: 'https://www.demo.com',
    timeout: 5000,
})

/** 请求拦截器 */
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 从store中获取token
        const {token} = store.getState().authSlice;
        // 在请求头中携带token
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        // console.log('发送请求：', config);
        return config;
    }
)

/** 响应拦截器 */
service.interceptors.response.use(
    (response: AxiosResponse<ResType>) => {
        console.log('响应拦截器：', response);
        const {code, message: msg, data} = response.data || {};
        if (code !== 200) {
            message.error(`${code}: ${msg}`);
            return Promise.reject(new Error(msg + '>_<'));
        }
        return data as any;
    },
    (error: AxiosError) => {
        console.log('响应拦截器(错误)：', error);
        return Promise.reject(error);
    }
)

export default service;